package com.echo.neocommunity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.echo.neocommunity.pojo.DiscussPost;
import com.echo.neocommunity.pojo.MyPage;
import com.echo.neocommunity.pojo.User;
import com.echo.neocommunity.service.impl.DiscussPostServiceImpl;
import com.echo.neocommunity.service.impl.LikeService;
import com.echo.neocommunity.service.impl.UserServiceImpl;
import com.echo.neocommunity.utils.CommunityConstant;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
//@RequestMapping("/community")
public class HomeController {

    @Autowired
    private DiscussPostServiceImpl discussPostService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private LikeService likeService;

    @GetMapping("/index")
    public String getIndexPage(Model model, HttpServletRequest request){
        String current = request.getParameter("current");
        int pageNum=1;
        if(current!=null){
            pageNum=Integer.valueOf(current);
        }
        Page<DiscussPost> page=new Page<>(pageNum,10);
        discussPostService.page(page);
        long total = page.getTotal();
        long pages = page.getPages();
        QueryWrapper<DiscussPost> discussPostQueryWrapper=new QueryWrapper<>();
        discussPostQueryWrapper.orderByDesc("type").orderByDesc("create_time");
        discussPostService.page(page,discussPostQueryWrapper);
        MyPage myPage=new MyPage((long) pageNum,total,pages,"/index");
        List<DiscussPost> discussPost = page.getRecords();
        List<Map<String,Object>> list=new ArrayList<>();
        if(discussPost.size()!=0){
            discussPost.forEach((discusspost)->{
                Map<String,Object> map=new HashMap<>();
                map.put("post",discusspost);
                User userById = userService.getUserById(discusspost.getUserId());
                map.put("user",userById);
                Long likeCount = likeService.getLikeCount(CommunityConstant.ENTITY_TYPE_POST, discusspost.getId());
                map.put("likeCount",likeCount);
                list.add(map);
            });
        }
        model.addAttribute("page",myPage);
        model.addAttribute("discussPosts",list);
        return "index";
    }


}
